package com.avic.system.service.impl;

import com.avic.system.common.util.AssertUtil;
import com.avic.system.common.util.ex.BizErrorCode;
import com.avic.system.common.util.ex.BizException;
import com.avic.system.controller.info.MenuPermissionInfo;
import com.avic.system.dal.model.SystemRole;
import com.avic.system.service.SystemRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * 系统角色serviceImpl
 *
 * @author: huangsheng
 * @date: 2017/10/19
 */
@Service("systemRoleService")
public class SystemRoleServiceImpl extends SystemAbstractServiceImpl implements SystemRoleService {

    /**
     * 获取角色数据
     */
    @Override
    public List<SystemRole> getSystemRoles() {

        return systemRoleMapper.queryRole();
    }

    /**
     * 新建角色
     */
    @Override
    public String createSystemRole(SystemRole systemRole) {

        AssertUtil.isTrue(systemRoleMapper.checkRoleName(systemRole.getRoleName()) <= 0, BizErrorCode.ROLE_NAME_IS_EXIST);
        try {
            String uuid = UUID.randomUUID().toString();
            logger.info("准备创建角色，ID = {}", uuid);
            systemRole.setId(uuid);
            int successInsertCount = systemRoleMapper.insertRole(systemRole);
            logger.info("成功插入 {} 条数据", successInsertCount);
            return uuid;
        } catch (DuplicateKeyException de) {
            logger.warn("主键重复，不可新增角色数据", de.getMessage());
            throw new BizException(BizErrorCode.ROLE_NAME_IS_EXIST);
        } catch (Exception e) {
            logger.error("创建角色时异常：{}", e.getMessage());
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "创建角色时异常");
        }
    }

    /**
     * 更新角色数据
     */
    @Override
    public void updateSystemRole(SystemRole systemRole) {
        SystemRole querySystemRole = systemRoleMapper.queryRoleByRoleId(systemRole.getId());
        AssertUtil.isTrue(null != querySystemRole, BizErrorCode.ROLE_IS_NOE_EXIST);
        logger.info("查询到角色数据： getRoleName = {}", systemRole.getRoleName());

        if (StringUtils.isNotBlank(systemRole.getRoleName())) {
            if (!StringUtils.equals(systemRole.getRoleName(), querySystemRole.getRoleName())) {
                AssertUtil.isTrue(systemRoleMapper.checkRoleName(systemRole.getRoleName()) <= 0, BizErrorCode.ROLE_NAME_IS_EXIST);
            }
            try {
                logger.info("准备修改角色，ID = {}", systemRole.getId());
                int successUpdateCount = systemRoleMapper.updateSystemRole(systemRole);
                logger.info("成功执行 {} 条数据", successUpdateCount);
            } catch (DuplicateKeyException de) {
                logger.warn("主键重复，不可新增角色数据", de.getMessage());
                throw new BizException(BizErrorCode.ROLE_NAME_IS_EXIST);
            } catch (Exception e) {
                logger.error("修改角色时异常：{}", e);
                throw new BizException(BizErrorCode.SYSTEM_ERROR, "修改角色执行数据库异常");
            }
        }
    }

    /**
     * 删除角色数据
     */
    @Override
    public void deleteSystemRole(String roleId) {
        try {
            int successDeleteCount = systemRoleMapper.deleteSystemRole(roleId);
            logger.info("成功执行 {} 条数据", successDeleteCount);
        } catch (Exception e) {
            logger.error("删除角色时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "删除角色数据执行数据库异常");
        }
    }

    /**
     * 保存角色权限
     *
     * @param roleId        角色ID
     * @param permissionIds 权限ID集合
     */
    @Transactional
    @Override
    public void saveRolePermission(String roleId, List<String> permissionIds) {
        try {
            SystemRole systemRole = systemRoleMapper.queryRoleByRoleId(roleId);
            AssertUtil.isNotNull(systemRole, BizErrorCode.ROLE_IS_NOT_EXIST);

            int i = rolePermissionMapper.deletePermissionByRoleId(roleId);
            logger.info("成功执行删除：{}", i);
            if (null != permissionIds && permissionIds.size() > 0) {
                permissionIds.removeAll(Collections.singleton(MenuPermissionInfo.EMPTY_TREE_ID));
                rolePermissionMapper.batchInsertRolePermission(roleId, permissionIds);
                logger.info("批量插入{}条数据", permissionIds.size());
            }
        } catch (Exception e) {
            logger.error("保存角色权限：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "保存角色权限执行数据库异常");
        }
    }
}
